import React, { useState } from 'react'
import { Card, Row, Col, Table, Tag, Input } from 'antd'
import { useRequest, useMount } from 'ahooks'
import moment from 'moment'
import { CheckCircleOutlined, SyncOutlined, CloseCircleOutlined, MinusCircleOutlined } from '@ant-design/icons'

import { COMMUNICATION_APPLICATION_STATUS } from '@/pages/Dashboard/components/CrossChain/enums'
import { listApplications } from '@/pages/Dashboard/components/CrossChain/service'
import NewCrossChainApplication from './components/New'

const searchOption = {
  page: 1,
  per_page: 10,
  id__contains: '',
}

const CrossChainApplication = () => {
  const [modalVisible, setModalVisible] = useState(false)
  const [list, setList] = useState([])
  const [total, setTotal] = useState(0)
  const { loading, run: getApplications } = useRequest(listApplications, { manual: true })

  const queryApplications = async(params = {}) => {
    const { status, data = {}} = await getApplications({
      ...params,
      ...searchOption,
    })
    if (status === 200) {
      setTotal(data.total || 0)
      setList(data.data || [])
    }
  }

  const handleTableChange = (pagination) => {
    const { current, pageSize } = pagination
    searchOption.page = current
    searchOption.per_page = pageSize
    queryApplications()
  }

  const onSearch = (value) => {
    searchOption.contract_name__contains = value
    searchOption.page = 1
    queryApplications()
  }

  useMount(() => {
    queryApplications()
  })

  return (
    <div>
      <Card style={{ marginTop: 24 }}>
        <Row style={{ marginBottom: 18 }}>
          <Col span={24} style={{ textAlign: 'right' }}>
            <Input.Search allowClear style={{ width: '260px' }} placeholder="输入合约名称" onSearch={onSearch} />
          </Col>
        </Row>
        <Table
          dataSource={list}
          columns={columns}
          rowKey="id"
          loading={loading}
          onChange={handleTableChange}
          pagination={{
            current: searchOption.page,
            pageSize: searchOption.per_page,
            position: ['bottomCenter'],
            showTotal: (total, range) => `共 ${total} 条记录 第 ${range[0]}-${range[1]} 项`,
            showSizeChanger: true, showQuickJumper: true,
            total,
          }} />
      </Card>
      <NewCrossChainApplication visible={modalVisible} onCancel={() => setModalVisible(false)} />
    </div>
  )
}

const voteStatusEnum = Object.freeze({
  applied: '未投票',
  applying: '未投票',
  rejected: '已投票',
  connected: '已投票',
  error: '出错',
})

const voteResultEnum = {
  success: {
    label: '成功',
    color: 'success',
    icon: <CheckCircleOutlined />,
  },
  inProcess: {
    label: '投票中',
    color: 'processing',
    icon: <SyncOutlined spin />,
  },
  failed: {
    label: '失败',
    color: 'error',
    icon: <CloseCircleOutlined />,
  },
  default: {
    label: '未知',
    color: 'default',
    icon: <MinusCircleOutlined />,
  },
}

const columns = [
  {
    title: '申请ID',
    dataIndex: 'id',
    key: 'id',
  },
  {
    title: '来源链',
    dataIndex: 'source_name',
    key: 'source',
  },
  {
    title: '目标链',
    dataIndex: 'target_name',
    key: 'target',
  },
  {
    title: '申请时间',
    dataIndex: 'created_at',
    key: 'createdAt',
    render: (v) => v ? moment(v).format('YYYY-MM-DD HH:mm:ss') : '--',
  },
  {
    title: '投票状态',
    dataIndex: 'status',
    key: 'status',
    render: (text) => {
      const statusConfig = COMMUNICATION_APPLICATION_STATUS[text] || {}
      return <Tag color={['connected', 'rejected'].includes(statusConfig.value) ? 'success' : 'error'}>
        {voteStatusEnum[statusConfig.value]}
      </Tag>
    },
  },
  {
    title: '投票结果',
    dataIndex: 'status',
    key: 'voteResult',
    render: (text, record) => {
      const value = (COMMUNICATION_APPLICATION_STATUS[text] || {}).value
      let status = ''
      if (['applying', 'applied'].includes(value)) {
        status = 'inProcess'
      } else if (['connected'].includes(value)) {
        status = 'success'
      } else {
        status = 'failed'
      }
      const result = voteResultEnum[status]
      return <Tag color={result.color} icon={result.icon}>{result.label}</Tag>
    },
  },
]

export default CrossChainApplication
